#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include "img_sender.h"

int send_file(char *filename) {
  struct stat file_stat;
  char *buf;
  int offset;
  int ret;
  int blocksize;
  int fd;

  if (stat(filename, &file_stat) != 0) {
    printf("stat'ing %s not possible\n", filename);
    return -1;
  }
  /* reading the file to memory */
  fd = open(filename, O_RDONLY);
  buf = malloc(sizeof(char) * file_stat.st_size);
  offset = 0;
  blocksize = file_stat.st_blksize;
  do {
    if (offset + blocksize > file_stat.st_size) {
      blocksize = file_stat.st_size-offset;
    }
    /* printf("%d\n", blocksize); */
    ret = read(fd, buf+offset, blocksize);
    if (ret > 0) {
      offset += ret;
    }
  } while ((offset < file_stat.st_size) && (ret != -1));
  printf("read file %s, size %d, now sending\n", 
	 filename, (int) file_stat.st_size); 
  /* sending file */
  if (img_send(buf, file_stat.st_size) != 0) {
    printf("sending failed\n");
  } else {
    printf("   sending succeeded\n");
  }
  /* cleanup */
  free(buf);
  return 0;
}

/* Acceps several files as command line arguments that 
 * are sent as blocks to the default host:port.
 * If no file is given "dummy.png" is sent
 */
int main(int argc, char *argv[]) {
  int ret = -1;
  printf("Sending images\n");
  if (argc == 1) {
    ret = send_file("dummy.png");
  } else {
    int i;
    for (i=1; i < argc; i+=1) {
      ret = send_file(argv[i]);
      if (ret != 0)
	return ret;
    }
  }
  return ret;
}
